﻿using NoteHelper.IBusiness;
using NoteHelper.Utils;
using System;
using System.Collections;
using System.Data;
using System.Drawing;
using Unity;

namespace NoteHelper
{
    public partial class ArticleListForm : WeifenLuo.WinFormsUI.Docking.DockContent, IBaseView
    {
        private const string Pre = "Data_";
        private log4net.ILog logger;
        private DevAge.ComponentModel.IBoundList bd;
        public ArticleListForm()
        {
            InitializeComponent();
        }

        public int NoteId
        {
            get
            {
                var selectedRows = displayGrid.Selection.GetSelectionRegion().GetRowsIndex();
                if (selectedRows.Length == 0) return -1;
                var index = selectedRows[0];
                if (index < 1) return -1;

                return index;
            }
        }

        private void ArticleListForm_Load(object sender, EventArgs e)
        {
            logger = log4net.LogManager.GetLogger("NoteHelper.ArticleListForm");
            var container = UnityHelper.GetContainer();
            var articleManager = container.Resolve<IArticleManager>();
            displayGrid.FixedRows = 1;
            displayGrid.FixedColumns = 1;
            CreateColumns();

            searchbar1.ExecuteSearch += ExecuteCommand;
            var controller = new ArticleListFormController(this, articleManager);
        }

        private void CreateColumns()
        {
            SourceGrid.DataGridColumn gridColumn;
            gridColumn = displayGrid.Columns.Add("$_rowIndex", "下标", typeof(string));
            gridColumn.Width = 20;
            gridColumn.Visible = false;
            gridColumn = displayGrid.Columns.Add("ObjectID", "编号", typeof(string));
            gridColumn.Width = 80;
            gridColumn.AutoSizeMode = SourceGrid.AutoSizeMode.Default;

            gridColumn = displayGrid.Columns.Add("Description", "描述", typeof(string));
            gridColumn.Width = 400;
            gridColumn.AutoSizeMode = SourceGrid.AutoSizeMode.EnableAutoSize | SourceGrid.AutoSizeMode.EnableStretch;

            gridColumn = displayGrid.Columns.Add(null, "", new SourceGrid.Cells.Link());
            SourceGrid.Cells.Controllers.Button linkEvents = new SourceGrid.Cells.Controllers.Button();
            linkEvents.Executed += new EventHandler(linkEvents_Executed);
            gridColumn.DataCell.AddController(linkEvents);

            SourceGrid.Cells.Views.Link viewLink = new SourceGrid.Cells.Views.Link();
            viewLink.ImageAlignment = DevAge.Drawing.ContentAlignment.MiddleCenter;
            viewLink.TextAlignment = DevAge.Drawing.ContentAlignment.MiddleCenter;
            gridColumn.DataCell.View = viewLink;
            ((SourceGrid.Cells.Link)gridColumn.DataCell).Image = GlobalResource.打开ToolStripButton_Image;
            gridColumn.Width = 30;
            gridColumn.AutoSizeMode = SourceGrid.AutoSizeMode.Default;
        }

        private void ExecuteCommand(string cmd)
        {
            switch (cmd)
            {
                case ":n":
                    Insert?.Invoke(null, null);
                    break;

                case ":e":
                    Edit?.Invoke(null, null);
                    break;

                case ":d":
                    Remove?.Invoke(null, null);
                    break;

                case ":h":
                    Help?.Invoke(null, null);
                    break;

                case ":c":
                    Copy?.Invoke(null, null);
                    break;

                case ":p":
                    Print?.Invoke(null, null);
                    break;

                default:
                    RowData = new Hashtable();
                    RowData.Add("keyword", cmd);
                    Query?.Invoke(null, null);
                    break;
            }
        }
        #region ==== IBaseView Impl ====

        private DataTable _displayList;
        public DataTable DisplayList
        {
            get { return _displayList; }
            set
            {
                if (value == null) return;
                _displayList = value;

                bd = new DevAge.ComponentModel.BoundDataView(_displayList.DefaultView);
                bd.AllowNew = false;
                bd.AllowEdit = false;
                bd.AllowDelete = false;
                displayGrid.DataSource = bd;
            }
        }
        public FormCommand Cmd { get; set; }
        public Hashtable RowData { get; set; }

        public event EventHandler Insert;
        public event EventHandler Edit;
        public event EventHandler Remove;
        public event EventHandler Copy;
        public event EventHandler Query;
        public event EventHandler Accept;
        public event EventHandler Cancel;
        public event EventHandler Print;
        public event EventHandler Help;
        
        #endregion

        #region ==== Toolbar Event ====
        /// <summary>
        /// 添加
        /// </summary>
        private void InsertButtonClick(object sender, EventArgs e)
        {
            Insert?.Invoke(sender, e);
        }
        /// <summary>
        /// 修改
        /// </summary>
        private void EditButtonClick(object sender, EventArgs e)
        {
            Edit?.Invoke(sender, e);
        }
        /// <summary>
        /// 删除
        /// </summary>
        private void RemoveButtonClick(object sender, EventArgs e)
        {
            var dockPanel = this.DockHandler.DockPanel;
            var rowIndex = GetRowIndex();
            if (rowIndex == -1) return;

            var row = DisplayList.Rows[rowIndex];
            int id = int.Parse(row["ObjectID"].ToString());
            string text = $"Note{id}";
            var content = dockPanel.FindDocument(text);
            if (content != null)
            {
                content.DockHandler.Close();
            }
            if (AlterMsg.Confirm(displayGrid.DeleteQuestionMessage))
            {
                Remove?.Invoke(sender, e);
            }
        }
        /// <summary>
        /// 复制
        /// </summary>
        private void CopyButtonClick(object sender, EventArgs e)
        {            
            Copy?.Invoke(sender, e);
        }
        /// <summary>
        /// 查询
        /// </summary>
        private void QueryButtonClick(object sender, EventArgs e)
        {
            Query?.Invoke(sender, e);
        }
        /// <summary>
        /// 确定
        /// </summary>
        private void AcceptButtonClick(object sender, EventArgs e)
        {
            Accept?.Invoke(sender, e);
        }
        /// <summary>
        /// 取消
        /// </summary>
        private void CancelButtonClick(object sender, EventArgs e)
        {
            Cancel?.Invoke(sender, e);
        }
        /// <summary>
        /// 打印
        /// </summary>
        private void PrintButtonClick(object sender, EventArgs e)
        {
            Print?.Invoke(sender, e);
        }
        /// <summary>
        /// 帮助
        /// </summary>
        private void HelpButtonClick(object sender, EventArgs e)
        {
            Help?.Invoke(sender, e);
        }

        public void Notify(string notification)
        {
            AlterMsg.Info(notification);
        }
        #endregion

        private void linkEvents_Executed(object sender, EventArgs e)
        {
            var cellContext = (SourceGrid.CellContext)sender;
            SourceGrid.DataGrid grid = (SourceGrid.DataGrid)cellContext.Grid;
            int rowIndex = cellContext.Position.Row;
            grid.Selection.SelectRow(rowIndex, true);
            rowIndex = GetRowIndex();
            var row = DisplayList.Rows[rowIndex];
            int id = int.Parse(row["ObjectID"].ToString());
            ShowPanel(id);
        }

        private void ShowPanel(int id)
        {
            var dockPanel = this.DockHandler.DockPanel;
            string text = $"Note{id}";
            var content = dockPanel.FindDocument(text);
            if (content != null)
            {
                content.DockHandler.Activate();
            }
            else
            {
                var dummyDoc = new ArticleBaseForm(id);
                dummyDoc.Show(dockPanel);
            }
        }

        public void BeginEdit()
        {
            ShowPanel(0);
        }
        public void EndEdit() { }

        public int GetRowIndex()
        {
            int rowIndex = -1;
            object[] rows = displayGrid.SelectedDataRows;
            if (rows != null && rows.Length > 0)
            {
                DataRowView row = (DataRowView)rows[0];
                int.TryParse(row["$_rowIndex"].ToString(), out rowIndex);
            }
            return rowIndex;
        }
    }
}
